package com.lkd.business;

import com.lkd.annotations.ProcessType;
import com.lkd.common.VMSystem;
import com.lkd.contract.SupplyCfg;
import com.lkd.feignService.VMService;
import com.lkd.http.viewModel.TaskDetailsViewModel;
import com.lkd.http.viewModel.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.viewmodel.VendingMachineViewModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Component
@ProcessType(value = "supplyTask")
@Slf4j
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            //解析协议内容
            SupplyCfg supplyCfg = JsonUtil.getByJson(jsonMsg, SupplyCfg.class);
            if (supplyCfg == null) return;
            //找出被指派人
            VendingMachineViewModel vmInfo = vmService.getVMInfo(supplyCfg.getInnerCode());
            Integer userId = taskService.getLeastUser(vmInfo.getRegionId(), false);

            //创建补货工单
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0); //创建类型
            taskViewModel.setUserId(userId);
            taskViewModel.setInnerCode(supplyCfg.getInnerCode());
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setDesc("自动补货工单");

            taskViewModel.setDetails(supplyCfg.getSupplyData().stream().map(c -> {
                TaskDetailsViewModel detailsViewModel = new TaskDetailsViewModel();
                detailsViewModel.setSkuId(c.getSkuId());
                detailsViewModel.setChannelCode(c.getChannelId());
                detailsViewModel.setExpectCapacity(c.getCapacity());
                detailsViewModel.setSkuName(c.getSkuName());
                detailsViewModel.setSkuImage(c.getSkuImage());
                return detailsViewModel;
            }).collect(Collectors.toList()));//补货详情
            taskService.createTask(taskViewModel);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错：" + e.getMessage());
        }
    }
}
